<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.example.ks.entity.User, java.util.List, com.example.ks.entity.Order, java.util.Map" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>宠物服务预约</title>
  <!-- 引入 Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            secondary: '#10B981',
            warning: '#F59E0B',
            danger: '#EF4444'
          }
        }
      }
    }

    // 表单验证并设置隐藏字段的值
    function validateAndSetFormData(form, adminId) {
      // 获取当前登录用户ID（从JavaScript变量获取）
      const userId = document.getElementById('currentUserId').value;

      // 设置userId隐藏字段
      form.querySelector('[name="userId"]').value = userId;

      // 获取输入值
      const startTime = document.getElementById('startTime_' + adminId).value;
      const serviceItem = document.getElementById('serviceItem_' + adminId).value;
      const petName = document.getElementById('petName_' + adminId).value;

      if (!startTime || !serviceItem || !petName) {
        alert('所有字段都必须填写！');
        return false;
      }

      // 设置隐藏字段的值
      document.getElementById('startTimeHidden_' + adminId).value = startTime;
      document.getElementById('serviceItemHidden_' + adminId).value = serviceItem;
      document.getElementById('petNameHidden_' + adminId).value = petName;

      return true;
    }
  </script>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="container mx-auto px-4 py-8 max-w-6xl">
  <div class="bg-white rounded-xl shadow-md p-6 mb-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-3xl font-bold text-gray-800">宠物服务预约</h1>
        <p class="text-gray-600">管理您的宠物服务预约</p>
      </div>
      <div class="flex space-x-3">
        <form action="user-index" method="get">
          <input type="hidden" name="action" value="appointment">
          <button type="submit" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition flex items-center">
            <i class="fa fa-calendar-plus-o mr-2"></i>我要预约
          </button>
        </form>
        <form action="user-my-order" method="get">
          <button type="submit" class="bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg transition flex items-center">
            <i class="fa fa-list mr-2"></i>查看我的订单
          </button>
        </form>
        <a href="logout" class="bg-danger hover:bg-danger/90 text-white px-4 py-2 rounded-lg transition flex items-center">
          <i class="fa fa-sign-out mr-2"></i>退出登录
        </a>
      </div>
    </div>

    <!-- 隐藏的当前用户ID -->
    <input type="hidden" id="currentUserId" value="<%= session.getAttribute("user") != null ? ((User)session.getAttribute("user")).getId() : 0 %>">

    <% if (request.getAttribute("error") != null) { %>
    <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded">
      <p class="text-red-700"><%= request.getAttribute("error") %></p>
    </div>
    <% } %>

    <%
      // 修复点：同时从属性和参数中获取action
      String action = (String) request.getAttribute("action");
      if (action == null) {
        action = request.getParameter("action");
      }
      boolean showAppointment = action == null || "appointment".equals(action);
      boolean showOrders = "orders".equals(action);
    %>

    <!-- 预约表单区域 -->
    <% if (showAppointment) { %>
    <div class="overflow-x-auto rounded-lg shadow">
      <h2 class="text-xl font-bold text-gray-800 mb-4">预约服务</h2>
      <table class="min-w-full bg-white">
        <thead class="bg-gray-100">
        <tr>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">管理员姓名</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">开始时间</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">服务项目</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">宠物名称</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">操作</th>
        </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
        <%
          List<User> admins = (List<User>) request.getAttribute("admins");
          if (admins != null && !admins.isEmpty()) {
            for (User admin : admins) {
        %>
        <tr>
          <td class="py-4 px-4"><%= admin.getUsername() != null ? admin.getUsername() : "未命名" %></td>
          <td class="py-4 px-4">
            <input type="datetime-local" id="startTime_<%= admin.getId() %>"
                   class="border border-gray-300 rounded px-3 py-2 w-full"
                   required
                   min="<%= new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm").format(new java.util.Date()) %>">
          </td>
          <td class="py-4 px-4">
            <select id="serviceItem_<%= admin.getId() %>"
                    class="border border-gray-300 rounded px-3 py-2 w-full"
                    required>
              <option value="宠物洗浴">宠物洗浴</option>
              <option value="宠物托管">宠物托管</option>
              <option value="宠物美容">宠物美容</option>
              <option value="宠物医疗">宠物医疗</option>
              <option value="宠物训练">宠物训练</option>
            </select>
          </td>
          <td class="py-4 px-4">
            <input type="text" id="petName_<%= admin.getId() %>"
                   class="border border-gray-300 rounded px-3 py-2 w-full"
                   placeholder="输入宠物名称"
                   required>
          </td>
          <td class="py-4 px-4">
            <form action="submit-appointment" method="post"
                  onsubmit="return validateAndSetFormData(this, <%= admin.getId() %>)">
              <input type="hidden" name="adminId" value="<%= admin.getId() %>">
              <input type="hidden" name="userId" value="0"> <!-- 将由JavaScript设置 -->
              <input type="hidden" name="startTime" id="startTimeHidden_<%= admin.getId() %>">
              <input type="hidden" name="serviceItem" id="serviceItemHidden_<%= admin.getId() %>">
              <input type="hidden" name="petName" id="petNameHidden_<%= admin.getId() %>">

              <button type="submit"
                      class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition w-full">
                <i class="fa fa-calendar-check-o mr-1"></i>确认预约
              </button>
            </form>
          </td>
        </tr>
        <%
          }
        } else {
        %>
        <tr>
          <td colspan="5" class="text-center py-8 text-gray-500">
            <i class="fa fa-inbox text-4xl mb-3"></i>
            <p>暂无可预约的管理员</p>
          </td>
        </tr>
        <% } %>
        </tbody>
      </table>
    </div>
    <% } %>

    <!-- 订单列表区域 -->
    <% if (showOrders) { %>
    <div class="overflow-x-auto rounded-lg shadow mt-8">
      <h2 class="text-xl font-bold text-gray-800 mb-4">我的订单</h2>

      <%
        List<Order> orders = (List<Order>) request.getAttribute("orders");
        Map<Integer, String> userNames = (Map<Integer, String>) request.getAttribute("userNames");
        if (orders != null && !orders.isEmpty()) {
      %>
      <table class="min-w-full bg-white">
        <thead class="bg-gray-100">
        <tr>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">管理员</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">开始时间</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">服务项目</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">宠物名称</th>
          <th class="py-3 px-4 text-left text-gray-700 font-semibold">状态</th>
        </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
        <%
          for (Order order : orders) {
        %>
        <tr>
          <td class="py-4 px-4"><%= userNames.get(order.getAdminId()) %></td>
          <td class="py-4 px-4"><%= order.getStartTime() %></td>
          <td class="py-4 px-4"><%= order.getServiceItem() %></td>
          <td class="py-4 px-4"><%= order.getPetName() %></td>
          <td class="py-4 px-4">
            <%
              String statusClass = "";
              switch (order.getStatus()) {
                case 0:
                  statusClass = "bg-yellow-100 text-yellow-800";
                  out.print("<span class='px-3 py-1 rounded-full text-sm " + statusClass + "'>服务未开始</span>");
                  break;
                case 1:
                  statusClass = "bg-blue-100 text-blue-800";
                  out.print("<span class='px-3 py-1 rounded-full text-sm " + statusClass + "'>服务进行中</span>");
                  break;
                case 2:
                  statusClass = "bg-green-100 text-green-800";
                  out.print("<span class='px-3 py-1 rounded-full text-sm " + statusClass + "'>服务已完成</span>");
                  break;
              }
            %>
          </td>
        </tr>
        <%
          }
        %>
        </tbody>
      </table>
      <% } else { %>
      <div class="text-center py-8 bg-gray-50 rounded-lg">
        <i class="fa fa-list-alt text-4xl text-gray-400 mb-3"></i>
        <p class="text-gray-500 text-lg">您还没有任何订单</p>
        <a href="user-index"
           class="mt-4 inline-block bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition">
          <i class="fa fa-plus mr-2"></i>立即预约
        </a>
      </div>
      <% } %>
    </div>
    <% } %>
  </div>
</div>
</body>
</html>